package com.lzx.iteam.net;

import android.content.Context;
import android.os.Message;
import com.lzx.iteam.bean.EventListData;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.provider.EventsMsgDB;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Megan on 15/11/25.
 */
public class EventDataMessage {

    public static class GetEventListMessage extends CcMsgStructure {

        private Message mmCallback;
        private CloudDBOperation cloudDBOperation;
        private EventsMsgDB mMsgDB;
        private PreferenceUtil mPreferenceUtil;
        private Context mContext;
        private String type;

        public GetEventListMessage(Message mCallback, Context mContext, String type) {
            this.mmCallback = mCallback;
            this.mContext = mContext;
            this.type = type;
            mPreferenceUtil = PreferenceUtil.getInstance(mContext);
            cloudDBOperation = new CloudDBOperation(mContext);
            mMsgDB = new EventsMsgDB(mContext);
        }

        @Override
        public void onReceive(JSONObject data) {
            final ArrayList<EventListData> list = new ArrayList<EventListData>();
            try {
                JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
                JSONArray item = jsonObject.getJSONArray("datas");
                mPreferenceUtil.save("event_count", jsonObject.getString("counts"));
                for (int i = 0; i < item.length(); i++) {
                    JSONObject object = item.getJSONObject(i);
                    final EventListData listData = new EventListData();
                    if(object.has("none")){
                        cloudDBOperation.deleteEventByEventId(object.getString("event_id"));
                    }else{
//                    listData.setUpdateTime(object.getString("update_time"));
                        //listData.setCreateTime(object.getString("create_time"));
                        listData.setUserType(object.getString("user_type"));
                        listData.setHasRead(object.getString("has_read"));
                        if(object.has("vote")){
                            listData.setVotes(object.getString("vote"));
                        }
                        if (object.has("has_join")) {
                            listData.setHasJoin(object.getString("has_join"));
                        }
                        if (object.has("_id")) {
                            listData.setId(object.getString("_id"));
                        }
                        if (object.has("reply") && object.getJSONObject("reply").length() > 0) {
                            JSONObject reply = object.getJSONObject("reply");
                            listData.setReplyLastName(reply.getString("uname"));
                            listData.setReplyLastContent(reply.getString("reply"));
                        }
                        JSONObject event = object.getJSONObject("event");
                        listData.setUpdateTime(event.getString("update_time"));
                        listData.setEventType(event.getString("event_type"));
                        listData.setEventId(event.getString("_id"));
                        listData.setUserId(event.getString("user_id"));
                        listData.setUserName(event.getString("user_name"));
                        if (event.has("user_img")) {
                            listData.setEventAvatar(event.getString("user_img"));
                        }
                        if (event.has("create_time")) {
                            String createTime = event.getInt("create_time") + "";
                            if (createTime.contains(".")) {
                                createTime = createTime.substring(0, createTime.length() - 3);
                            }
                            listData.setCreateTime(createTime);
                        }
                        if (event.has("qrcode")){
                            listData.setQrcode(event.getString("qrcode"));
                        }
                        listData.setMemberCount(event.getString("member_count"));
                        listData.setEventTitle(event.getString("event_title"));
                        if (event.has("has_read_count")) {
                            listData.setHasReadCount(event.getString("has_read_count"));
                        }
                        if (event.has("reply_count")) {
                            listData.setReplyCount(event.getString("reply_count"));
                        }
                        if (event.has("author")) {
                            listData.setAuthor(event.getString("author"));
                        }
                        if (event.has("attachment")) {
                            JSONArray image = event.getJSONArray("attachment");
                            StringBuilder thumbSb = new StringBuilder();
                            StringBuilder oriSb = new StringBuilder();
                            for (int k = 0; k < image.length(); k++) {
                                JSONObject imageObject = image.getJSONObject(k);
//                            if(imageObject.getString("type").equals("1"))
                                if (imageObject.has("thumb")) {
//                                Bitmap imageBitmap = ((BitmapDrawable) DownloadImageTask.loadImageFromNetwork(imageObject.getString("thumb"))).getBitmap();
//                                String imagePath = PhotoUtil.saveBitmaptoSdCard(imageBitmap, PhotoUtil.FOLDER_IMAGES_THUMBNAILS);
                                    thumbSb.append(imageObject.getString("thumb") + ",");
                                }
                                if (imageObject.has("ori")) {
                                    oriSb.append(imageObject.getString("ori") + ",");
                                }
                            }
                            if (thumbSb.length() > 0) {
                                listData.setThumbImage(thumbSb.substring(0, thumbSb.length() - 1));
                            }
                            if (oriSb.length() > 0) {
                                listData.setOriImage(oriSb.substring(0, oriSb.length() - 1));
                            }
                        }
                        if (event.has("join_count")) {
                            listData.setJoinCount(event.getString("join_count"));
                        }
                        if (event.has("event_address")) {
                            listData.setActivitySite(event.getString("event_address"));
                        }
                        if (event.has("event_date")) {
                            listData.setActivityTime(event.getString("event_date"));
                        }
                        if (event.has("event_time")) {
                            listData.setActivityTime(event.getString("event_time"));
                        }
                        if (event.has("event_templ_name")) {
                            listData.setEventName(event.getString("event_templ_name"));
                        } else {
                            listData.setEventName("");
                        }

                        final int count = mMsgDB.getUnReadCountOfOneEvent(event.getString("_id"));
                        listData.setUnReadCount(count + "");
                        if (event.getString("event_type").equals("7") || event.getString("event_type").equals("9")) {
                            listData.setContent1(event.getString("event_content"));
                        } else if (event.getString("event_type").equals("8")) {
                            StringBuilder votes = new StringBuilder();
                            JSONArray array = new JSONArray(event.getString("event_content"));
                            for (int j = 0;j<array.length();j++){
                                String vote = array.getJSONObject(j).getString("content");
                                votes.append(vote).append(",");
                            }
                            listData.setContent1(votes.toString());
                        } else {
                            JSONArray content = event.getJSONArray("event_content");
                            switch (content.length()) {
                                case 3:
                                    if (content.getJSONObject(2).has("content")) {
                                        listData.setContent3(content.getJSONObject(2).getString("content"));
                                    }
                                    if (content.getJSONObject(2).has("init_title")) {
                                        listData.setInitTitle3(content.getJSONObject(2).getString("init_title"));
                                    }
                                    if (content.getJSONObject(2).has("url")) {
                                        listData.setUrl3(content.getJSONObject(2).getString("url"));
                                    }
                                case 2:
                                    if (content.getJSONObject(1).has("content")) {
                                        listData.setContent2(content.getJSONObject(1).getString("content"));
                                    }
                                    if (content.getJSONObject(1).has("init_title")) {
                                        listData.setInitTitle2(content.getJSONObject(1).getString("init_title"));
                                    }
                                    if (content.getJSONObject(1).has("url")) {
                                        listData.setUrl2(content.getJSONObject(1).getString("url"));
                                    }

                                case 1:
                                    if (content.getJSONObject(0).has("content")) {
                                        listData.setContent1(content.getJSONObject(0).getString("content"));
                                    }
                                    if (content.getJSONObject(0).has("init_title")) {
                                        listData.setInitTitle1(content.getJSONObject(0).getString("init_title"));
                                    }
                                    if (content.getJSONObject(0).has("url")) {
                                        listData.setUrl1(content.getJSONObject(0).getString("url"));
                                    }

                                    break;
                            }
                        }
                        cloudDBOperation.insertEvent(listData);
                    }
                    list.add(listData);


                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (mmCallback != null) {
                mmCallback.obj = list;
                mmCallback.arg1 = 0;
                mmCallback.sendToTarget();
            }

        }

        @Override
        public void onError(int error, Object ret) {
            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }


    public static class GetEventListData extends CcMsgStructure {

        private Message mmCallback;
        private CloudDBOperation cloudDBOperation;
        private EventsMsgDB mMsgDB;
        private Context mContext;
        private String type;
        private int mPageIndex;
        private PreferenceUtil mPreferenceUtil;


        public GetEventListData(Message mCallback, Context mContext, String type,int pageIndex) {
            this.mmCallback = mCallback;
            this.mContext = mContext;
            this.mPageIndex=pageIndex;
            this.type = type;
            cloudDBOperation = new CloudDBOperation(mContext);
            mMsgDB = new EventsMsgDB(mContext);
            mPreferenceUtil = PreferenceUtil.getInstance(mContext);

        }

        @Override
        public void onReceive(JSONObject data) {
            final ArrayList<EventListData> list = new ArrayList<EventListData>();
            try {
                JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
                JSONArray item = jsonObject.getJSONArray("datas");
                mPreferenceUtil.save("event_count", jsonObject.getString("counts"));

                // TODO 第一次进来，且查询所有类型时清除数据库
                if(mPageIndex == 1 && "0".equals(type)){
                    cloudDBOperation.deleteAllEvents();
                }
                for (int i = 0; i < item.length(); i++) {
                    JSONObject object = item.getJSONObject(i);
                    final EventListData listData = new EventListData();
                    listData.setAllCounts(jsonObject.getString("counts"));
//                    listData.setUpdateTime(object.getString("update_time"));
                    listData.setUserType(object.getString("user_type"));
                    listData.setHasRead(object.getString("has_read"));
                    if(object.has("vote")){
                        listData.setVotes(object.getString("vote"));
                    }
                    if (object.has("has_join")) {
                        listData.setHasJoin(object.getString("has_join"));
                    }
                    if (object.has("_id")) {
                        listData.setId(object.getString("_id"));
                    }
                    if (object.has("reply") && object.getJSONObject("reply").length() > 0) {
                        JSONObject reply = object.getJSONObject("reply");
                        listData.setReplyLastName(reply.getString("uname"));
                        listData.setReplyLastContent(reply.getString("reply"));
                    }
                    JSONObject event = object.getJSONObject("event");
//                    listData.setUpdateTime(event.getString("update_time"));
                    listData.setEventType(event.getString("event_type"));
                    listData.setEventId(event.getString("_id"));
                    listData.setUserId(event.getString("user_id"));
                    listData.setUserName(event.getString("user_name"));
                    listData.setUpdateTime(event.getString("update_time"));
                    if (event.has("user_img")) {
                        listData.setEventAvatar(event.getString("user_img"));
                    }
                    if (event.has("max_choice_count")){
                        listData.setVoteMaxNumber(event.getString("max_choice_count"));
                    }
                    if (event.has("create_time")) {
                        String createTime = event.getInt("create_time") + "";
                        if (createTime.contains(".")) {
                            createTime = createTime.substring(0, createTime.length() - 3);
                        }
                        listData.setCreateTime(createTime);
                    }
                    if (event.has("end_datetime")){
                        listData.setEndTime(event.getString("end_datetime"));
                    }
                    if (event.has("is_qrcode")){
                        listData.setIsQrcode(event.getString("is_qrcode"));
                    }
                    if (event.has("qrcode")){
                        listData.setQrcode(event.getString("qrcode"));
                    }
                    listData.setMemberCount(event.getString("member_count"));
                    listData.setEventTitle(event.getString("event_title"));
                    if (event.has("has_read_count")) {
                        listData.setHasReadCount(event.getString("has_read_count"));
                    }
                    if (event.has("reply_count")) {
                        listData.setReplyCount(event.getString("reply_count"));
                    }
                    if (event.has("author")) {
                        listData.setAuthor(event.getString("author"));
                    }
                    if (event.has("attachment")) {
                        JSONArray image = event.getJSONArray("attachment");
                        StringBuilder thumbSb = new StringBuilder();
                        StringBuilder oriSb = new StringBuilder();
                        for (int k = 0; k < image.length(); k++) {
                            JSONObject imageObject = image.getJSONObject(k);
//                            if(imageObject.getString("type").equals("1"))
                            if (imageObject.has("thumb")) {
//                                Bitmap imageBitmap = ((BitmapDrawable) DownloadImageTask.loadImageFromNetwork(imageObject.getString("thumb"))).getBitmap();
//                                String imagePath = PhotoUtil.saveBitmaptoSdCard(imageBitmap, PhotoUtil.FOLDER_IMAGES_THUMBNAILS);
                                thumbSb.append(imageObject.getString("thumb") + ",");
                            }
                            if (imageObject.has("ori")) {
                                oriSb.append(imageObject.getString("ori") + ",");
                            }
                        }
                        if (thumbSb.length() > 0) {
                            listData.setThumbImage(thumbSb.substring(0, thumbSb.length() - 1));
                        }
                        if (oriSb.length() > 0) {
                            listData.setOriImage(oriSb.substring(0, oriSb.length() - 1));
                        }
                    }
                    if (event.has("join_count")) {
                        listData.setJoinCount(event.getString("join_count"));
                    }
                    if (event.has("event_address")) {
                        listData.setActivitySite(event.getString("event_address"));
                    }
                    if (event.has("event_date")) {
                        listData.setActivityTime(event.getString("event_date"));
                    }
                    if (event.has("event_time")) {
                        listData.setActivityTime(event.getString("event_time"));
                    }
                    if (event.has("event_templ_name")) {
                        listData.setEventName(event.getString("event_templ_name"));
                    } else {
                        listData.setEventName("");
                    }

                    final int count = mMsgDB.getUnReadCountOfOneEvent(event.getString("_id"));
                    listData.setUnReadCount(count + "");
                    if (event.getString("event_type").equals("7") || event.getString("event_type").equals("9")) {
                        listData.setContent1(event.getString("event_content"));
                    } else if (event.getString("event_type").equals("8")) {
                        StringBuilder votes = new StringBuilder();
                        JSONArray array = new JSONArray(event.getString("event_content"));
                        for (int j = 0;j<array.length();j++){
                            String vote = array.getJSONObject(j).getString("content");
                            votes.append(vote).append(",");
                        }
                        listData.setContent1(votes.toString());
                    } else {
                        JSONArray content = event.getJSONArray("event_content");
                        switch (content.length()) {
                            case 3:
                                if (content.getJSONObject(2).has("content")) {
                                    listData.setContent3(content.getJSONObject(2).getString("content"));
                                }
                                if (content.getJSONObject(2).has("init_title")) {
                                    listData.setInitTitle3(content.getJSONObject(2).getString("init_title"));
                                }
                                if (content.getJSONObject(2).has("url")) {
                                    listData.setUrl3(content.getJSONObject(2).getString("url"));
                                }
                            case 2:
                                if (content.getJSONObject(1).has("content")) {
                                    listData.setContent2(content.getJSONObject(1).getString("content"));
                                }
                                if (content.getJSONObject(1).has("init_title")) {
                                    listData.setInitTitle2(content.getJSONObject(1).getString("init_title"));
                                }
                                if (content.getJSONObject(1).has("url")) {
                                    listData.setUrl2(content.getJSONObject(1).getString("url"));
                                }

                            case 1:
                                if (content.getJSONObject(0).has("content")) {
                                    listData.setContent1(content.getJSONObject(0).getString("content"));
                                }
                                if (content.getJSONObject(0).has("init_title")) {
                                    listData.setInitTitle1(content.getJSONObject(0).getString("init_title"));
                                }
                                if (content.getJSONObject(0).has("url")) {
                                    listData.setUrl1(content.getJSONObject(0).getString("url"));
                                }

                                break;
                        }
                    }
                    cloudDBOperation.insertEvent(listData);
                    list.add(listData);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (mmCallback != null) {
                mmCallback.obj = list;
                mmCallback.arg1 = 0;
                mmCallback.sendToTarget();
            }

        }

        @Override
        public void onError(int error, Object ret) {
            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

}
